<?php

namespace SinoPHP\BbdBoss\Library;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Upfor\UpforPHP\Library\Math;

/**
 * JWT(JSON Web Tokens)
 */
class JwtHelper {

    /**
     * iss claim
     */
    const ISS = 'BBD-BOSS';

    /**
     * exp claim
     */
    const EXP = 7200;

    /**
     * Build token
     *
     * @param  string  $secret
     * @param  string  $subject
     * @param  array   $contents
     * @param  integer $expire
     * @return \Lcobucci\JWT\Token
     */
    public static function buildToken($secret, $subject, array $contents = array(), $expire = null) {
        $builder = new Builder();

        // Configures the issuer (iss claim)
        $builder->setIssuer(self::ISS);

        // Configures the time that the token was issue (iat claim)
        $builder->setIssuedAt(time());

        // Configures the expiration time of the token (exp claim)
        if (!Math::isInt($expire) || $expire <= 0) {
            $expire = self::EXP;
        }
        $builder->setExpiration(time() + $expire);

        $builder->setSubject($subject);

        foreach ($contents as $key => $value) {
            $builder->set($key, $value);
        }

        // creates a signature using $secret as key
        $builder->sign(new Sha256(), $secret);

        return $builder->getToken();
    }

    public static function validateToken($token) {
        $data = new ValidationData();
        $data->setIssuer(self::ISS);
        $data->setCurrentTime(time());

        $token = (new Parser())->parse((string) $token);
        if (!$token->validate($data)) {
            return false;
        }

        return $token->getClaims();
    }

}
